#!/usr/bin/env python
###############################################################################################
#  Author:
_author = '<a href="mailto:debuti@gmail.com">Borja Garcia</a>'
# Program:
_name = 'backInTime.py'
# Descrip:
_description = '''This is the automatic installation of backInTime, providing methods
 to install, update, configure and uninstall the whole software.'''
# Version:
_version = '0.0.0'
#    Date:
_date = 'YYYY-MM-DD:hh:mm'
# License: This script doesn't require any license since it's not intended to be redistributed.
#          In such case, unless stated otherwise, the purpose of the author is to follow GPLv3.
# History: 0.0.0 (YYYY-MM-DD:hh:mm)
#            -Initial release
###############################################################################################

import sys
import os
import optparse
import subprocess
import pexpect
import time

# Global variables
rootNeeded = True

# Error declaration

error = { "" : "",
          "" : "",
          "" : "" }

# Public functions

def checkRoot():
    '''This function verifies if user is root
    '''

    if rootNeeded:
        if os.geteuid() != 0:
            return False
        else:
            return True
    else:
        return True

def install():
    '''This procedure installs the software 
    '''

    if not checkRoot():
        return -1
    else:
        orders = [["apt-get update",
                   "apt-get -y install backintime-gnome"],

                  ["dpkg -i res/meld_1.3.0-2_all.deb",
                   "dpkg -i res/nautilus-actions_1.10.1-1_i386.deb",
                   "dpkg -i res/backintime-common_0.9.26-3_all.deb",
                   "dpkg -i res/backintime-gnome_0.9.26-3_all.deb"]]


        for order in orders:
            allRetcode = True
            for command in order:
                child = pexpect.spawn(command)
                child.logfile = sys.stdout   # Uncomment to debug

                # do this to only to output!
                try:
                    child.expect("th3str1ngth4tn3v3rb3m4tched,onlyt0flush0utput")
                except:
                    pass
                
                # must die by now, but if not, give it a second chance
                while child.isalive():
                    pass
                if child.exitstatus == None or child.exitstatus != 0:
                    retcode = False
                else:
                    retcode = True
                
                allRetcode = allRetcode and retcode
                # if already goes wrong skip it
                if not allRetcode:
                    break
            # if everything goes ok, finish
            if allRetcode:
                break

        # output exit status
        if not allRetcode:
            return -1
        else:
            return 0

def configure():
    '''This procedure configures the software
    '''
    
    if not checkRoot():
        return -1
    else:
        return 0

def uninstall():
    '''This procedure uninstalls the software
    '''
    if not checkRoot():
        return -1
    else:
        return 0


def update():
    '''This procedure updates the software
    '''
    if not checkRoot():
        return -1
    else:
        return 0



# Entry point if called talcual to be selfstanding

if __name__ == '__main__':

    if not checkRoot():
        print "Need to be root"
        sys.exit(-1)

    p = optparse.OptionParser(description=_description,
                              prog=_name,
                              version=_version,
                              usage='''%prog [options]''')
    p.add_option('--install','-i', action="store_true", dest="install", help='Installs the software')
    p.add_option('--configure','-c', action="store_true", dest="configure", help='Configures the software')
    p.add_option('--remove','-r', action="store_true", dest="uninstall", help='Uninstalls the software')
    p.add_option('--update','-u', action="store_true", dest="update", help='Updates the software')

    #Parse the commandline
    options, arguments = p.parse_args()

    #Decide what to do
    # halt if only receives the program name
    if len(sys.argv) == 1 :
        p.print_help()
        sys.exit(-1)
    else:
        if options.install:
            install()
        if options.configure:
            configure()
        if options.uninstall:
            uninstall()
        if options.update:
            update()
